var XHR = {
    OK: 'OK',
    FAIL: 'FAIL',
    ajax: function(url, data, method, success, error) {
        $.ajax({
            url: url,
            data: data,
            success: function(data, status, xhr) {
                XHR.success(data, status, xhr, success, error);
            },
            error: function(data, status, xhr) {
                XHR.error(data, status, xhr, error);
            }
        });
    },
    process: function(data, status, xhr, fsucc, ferror) {
        XHR.success(data, status, xhr, fsucc, ferror);
    },
    error: function(data, status, xhr, ferror) {
        if(ferror) {
            ferror(data, status, xhr);
        } else {
            alert('Error in XHR module');
        }
    },
    success: function(data, status, xhr, fsucc, ferror) {
        if(typeof data == 'string') {
            try {
                data = jQuery.parseJSON(data);
            } catch(e) {
                XHR.error(data, status, xhr, ferror);
            }
        }
        if(data.fm) {
            for(var level in data.fm) {
                for(var imsg in data.fm[level]) {
                    FM.add(level, data.fm[level][imsg]);
                }
            }
        }
        if(data.redirect) {
            document.location = data.redirect;
        }
        if(data.css) {
            $('head').append(data.css);
        }

        var d = data.data;
        var html = data.html;
        if(fsucc) {
            fsucc(data.status, d, html, data, xhr);
        }
        if(data.js) {
            if(data.js.files) {
                for(var i in data.js.files) {
                    var file = data.js.files[i];
                    if($('script[src="' + file + '"]').length == 0) {
                        var html = '<script type="text/javascript" src="' + file + '"></script>';
                        $('head').append(html);
                    }
                }
            }
            if(data.js.code) {
                for(var i in data.js.code) {
                    var code = data.js.code[i];
                    var html = '<script type="text/javascript">' + code + '</script>';
                    $('head').append(html);
                }
            }
        }
    }
};